from ..bot_plugin import Bot_plugin
from cqhttp import CQHttp
from bot_body import Bot_body
import logging
import colorful
from ..authorize_plugin.authorize_plugin import Group_manager
from tools.CQ_tools import group_msg_level


class Plugin_tiku(Bot_plugin):
    def __init__(self, bot_body: Bot_body, extra_master_qqs=[], name="tiku"):
        Bot_plugin.__init__(self, bot_body, extra_master_qqs=extra_master_qqs, name=name)
        self.authorizer = Group_manager(
            dbfile = r'./data/shuati.db',
            tbl = 'authorization',
            primary_column = 'qq'
        )
        self.tiku = Group_manager(
            dbfile = r'./data/tiku.db',
            tbl = 'quesstion',
            primary_column='topicId'
        )
        self.help_msg=r"""【题库助手帮助】
0. 题库帮助： 显示本条消息
1. 题库增加次数123456 123：为QQ为123456的用户增加123次搜索机会【仅主人】
2. 题库增加次数@123456 123：为被at的用户增加123次搜索机会【仅主人】
3. 题库查询次数：查询自己还剩多少次
4. 题库查询次数123456：查询QQ为123456的用户还剩多少次【仅主人】
5. 题库搜索会计的职责：显示最多10条包含【会计的职责】的题目"""

    def register_all(self):
        self.register('message')


    def query_times(self, qq):
        times = self.authorizer.query(qq, 'times')
        if times == None:
            times = 0
        return times
            
    def add_times(self, qq, times):
        now_times = self.query_times(qq) + times
        self.authorizer.update(qq, 'times', now_times)

    def search_tiku(self, text):
        sql = r'select subjectid, topic, option, anwes from quesstion where topic like "%{text}%" or option like "%{text}%"'.format(
            text=text
        )
        print("sql={}".format(sql))
        ret = self.tiku.execute(sql)
        return ret


    def handle_msg(self, context):
        raw_message = context['raw_message']
        msg_level = group_msg_level.judge(context, master_qqs=self.master_qqs)
        bot = self.bot
        reply_msg = "[CQ:at,qq={}]\n".format(context['user_id'])
        if raw_message == '题库帮助' and msg_level >= group_msg_level.MEMBER:
            bot.send(context, self.help_msg)
        elif raw_message[:6] == '题库增加次数' and msg_level >= group_msg_level.MASTER:
            import re
            pattern = r"题库增加次数{qq} {times}".format(
                qq = r"((?P<qq>\d{5,10})|\[CQ:at,qq=(?P<qq_at>\d{5,10})\])",
                times = r"(?P<times>.*)"
            )
            ret = re.search(pattern, raw_message)
            if ret == None:
                bot.send(context, self.help_msg)
                return
            d = ret.groupdict()
            qq = d['qq'] if d['qq'] != None else d['qq_at']
            times = d['times']
            qq, times = int(qq), int(times)
            old_times = self.query_times(qq)
            self.add_times(qq, times)
            now_times = self.query_times(qq)
            reply_msg = reply_msg + "更新结果：{}次 --> {}次".format(old_times, now_times)
            bot.send(context, reply_msg)
            return
        elif raw_message == '题库查询次数' and msg_level >= group_msg_level.MEMBER:
            times = self.query_times(context['user_id'])
            reply_msg = reply_msg + "您的剩余使用次数：{}".format(times)
            bot.send(context, reply_msg)
            return
        elif raw_message[:6] == '题库查询次数' and msg_level >= group_msg_level.MASTER:
            qq = int(raw_message[6:])
            times = self.query_times(qq)
            reply_msg = reply_msg + "QQ为{}的用户剩余使用次数为：{}".format(
                qq,
                times
            )
            bot.send(context, reply_msg)
            return 
        elif raw_message[:4] == '题库搜索' and msg_level >= group_msg_level.MEMBER:
            qq = context['user_id']
            now_times = self.query_times(qq)
            if now_times <= 0:
                reply_msg = reply_msg + "您的剩余使用次数已用完！"
                bot.send(context, reply_msg)
                return
            text = raw_message[4:]
            if len(text) < 5:
                reply_msg = reply_msg + "至少给出5个字用来搜索！"
                bot.send(context, reply_msg)
                return
            ret = self.search_tiku(text)
            self.add_times(qq, -1)
            now_times = self.query_times(qq)
            if len(ret)==0:
                reply_msg = reply_msg + "搜索无结果！\n您的剩余使用次数：{}".format(now_times)
                bot.send(context, reply_msg, at_sender=True)
            else:
                ret = ret[:10]
                ret = [r"""【题干】{tigan}
【选项】{xuanxiang}
【答案】{daan}""".format(tigan=v[1],xuanxiang=v[2],daan=v[3]) for v in ret]
                reply_msg = reply_msg + "\n******************\n".join(ret)
                reply_msg = reply_msg + "\n您的剩余使用次数：{}".format(now_times)
                bot.send(context, reply_msg, at_sender=True)
            return

            